<?php
if(
	isset( $_POST['username'] ) &&
	isset( $_POST['password'] )
)
{
	include( 'library/dbconnect.php' );

	$username = mysql_real_escape_string( $_POST['username'] );
	$password = md5( $_POST['password'] );

	$sqlAuthUser = "SELECT u_id, u_password FROM tbl_users WHERE u_username = '". $username ."' LIMIT 1";

	if( !$qAuthUser = mysql_query( $sqlAuthUser ) )
	{
		$feedback[] = ':-( Seems like the database-server is missing. Contact support if this problem persists.';
	}
	else
	{
		if( mysql_num_rows( $qAuthUser ) == 0 )
		{
			$feedback[] = ':-( The username supplied is wrong please try again.';
			$formUsername = $username;
		}
		else
		{
			$rUser = mysql_fetch_assoc( $qAuthUser );

			if( $password != $rUser['u_password'] )
			{
				$success = 0;

				$feedback[] = ':-( The password supplied is wrong please try again';
				$formUsername = $username;
			}
			else
			{
				$success = 1;

				session_start();
				$_SESSION['u_id'] = $rUser['u_id'];
			}

			$sqlLogAttempt = 	"INSERT INTO tbl_logins( l_username, l_ip, l_success ) VALUES('". $username ."', '". $_SERVER['REMOTE_ADDR'] ."', ". $success .")";

			mysql_query( $sqlLogAttempt );

			if( $success )
			{
				header( 'location: admin/' );
				exit;
			}
		}
	}
}
else
{
	$feedback[] = 'Du kunde inte loggas in pga bristande data.';
}
?>